<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="图片" prop="picture">
            <UploadImg v-model="formData.picture" />
          </el-form-item>
          <el-form-item label="标签" prop="tag">
            <el-select v-model="formData.tag" placeholder="请选择标签">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_TAG)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="品牌" prop="brandId">
            <select-brand-com v-model="formData.brandId"/>
          </el-form-item>
          <el-form-item label="系列" prop="series">
            <select-brand-series-com v-model="formData.series" :brand-id="formData.brandId"/>
          </el-form-item>
          <el-form-item label="分类" prop="type">
            <el-select v-model="formData.type" placeholder="请选择分类">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="阶段" prop="stage">
            <el-select v-model="formData.stage" placeholder="请选择阶段">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_STAGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="适用年龄" prop="age">
            <el-select v-model="formData.age" placeholder="请选择适用年龄">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_AGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品特点" prop="feature">
            <el-select v-model="formData.feature" placeholder="请选择产品特点" multiple>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_FEATURE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成分单位" prop="nutrientsType">
            <el-select v-model="formData.nutrientsType" placeholder="请选择营养成分单位" multiple>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="formData.sort" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="基本参数" name="second">
          <el-form-item label="净含量" prop="weight">
            <el-input v-model="formData.weight" placeholder="请输入净含量" />
          </el-form-item>
          <el-form-item label="参考价" prop="price">
            <el-input v-model="formData.price" placeholder="请输入参考价" />
          </el-form-item>
          <el-form-item label="注册号" prop="registerNo">
            <el-input v-model="formData.registerNo" placeholder="请输入注册号" />
          </el-form-item>
          <el-form-item label="版本" prop="version">
            <el-select v-model="formData.version" placeholder="请选择版本">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_VERSION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生产厂家" prop="producer">
            <el-input v-model="formData.producer" placeholder="请输入生产厂家" />
          </el-form-item>
          <el-form-item label="产地" prop="producePlace">
            <el-select v-model="formData.producePlace" placeholder="请选择产地">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_PLACE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="奶源" prop="origin">
            <el-select v-model="formData.origin" placeholder="请选择奶源">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_ORIGIN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="强化配方" name="third">
          <el-form-item label="基础强化" prop="baseStrengthen">
            <el-select v-model="formData.baseStrengthen" placeholder="请选择基础强化" multiple>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_BASE_STRENGTHEN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="特色强化" prop="fineStrengthen">
            <el-select v-model="formData.fineStrengthen" placeholder="请选择特色强化" multiple>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_FINE_STRENGTHEN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="配料表" name="four">
          <el-form-item label="原料表" prop="material">
            <el-select v-model="formData.material" placeholder="请选择原料表" multiple>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.AIB_MILK_MATERIAL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配料表" prop="formula">
            <el-input v-model="formData.formula" placeholder="请输入配料表" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="奶粉营养成分" name="five">
          <MilkNutrientsForm ref="milkNutrientsFormRef" :milk-id="formData.id" />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { MilkApi, MilkVO } from '@/api/aib/milk'
import MilkNutrientsForm from './components/MilkNutrientsForm.vue'
import SelectBrandCom from "@/views/aib/brand/components/SelectBrandCom.vue";
import SelectBrandSeriesCom from "@/views/aib/brandseries/components/SelectBrandSeriesCom.vue";

/** 奶粉信息 表单 */
defineOptions({ name: 'MilkForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const activeName = ref('first')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  picture: undefined,
  tag: undefined,
  brandId: undefined,
  series: undefined,
  type: undefined,
  stage: undefined,
  age: undefined,
  weight: undefined,
  price: undefined,
  registerNo: undefined,
  version: undefined,
  producer: undefined,
  producePlace: undefined,
  origin: undefined,
  formula: undefined,
  material: undefined,
  feature: undefined,
  baseStrengthen: undefined,
  fineStrengthen: undefined,
  nutrientsType: undefined,
  sort: undefined,
  status: undefined,
  remark: undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  picture: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  tag: [{ required: true, message: '标签不能为空', trigger: 'change' }],
  brandId: [{ required: true, message: '品牌不能为空', trigger: 'change' }],
  series: [{ required: true, message: '系列不能为空', trigger: 'change' }],
  type: [{ required: true, message: '分类不能为空', trigger: 'change' }],
  stage: [{ required: true, message: '阶段不能为空', trigger: 'change' }],
  age: [{ required: true, message: '适用年龄不能为空', trigger: 'change' }],
  weight: [{ required: true, message: '净含量不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '参考价不能为空', trigger: 'blur' }],
  registerNo: [{ required: true, message: '注册号不能为空', trigger: 'blur' }],
  version: [{ required: true, message: '版本不能为空', trigger: 'change' }],
  producer: [{ required: true, message: '生产厂家不能为空', trigger: 'blur' }],
  producePlace: [{ required: true, message: '产地不能为空', trigger: 'change' }],
  origin: [{ required: true, message: '奶源不能为空', trigger: 'change' }],
  formula: [{ required: true, message: '配料表不能为空', trigger: 'blur' }],
  material: [{ required: true, message: '原料表不能为空', trigger: 'change' }],
  nutrientsType: [{ required: true, message: '营养成分类型不能为空', trigger: 'change' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('milkNutrients')
const milkNutrientsFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MilkApi.getMilk(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await milkNutrientsFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'milkNutrients'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MilkVO
    // 拼接子表的数据
    data.milkNutrientss = milkNutrientsFormRef.value.getData()
    if (formType.value === 'create') {
      await MilkApi.createMilk(data)
      message.success(t('common.createSuccess'))
    } else {
      await MilkApi.updateMilk(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  }catch (error) {
    console.error('An error occurred:', error);
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    picture: undefined,
    tag: undefined,
    brandId: undefined,
    series: undefined,
    type: undefined,
    stage: undefined,
    age: undefined,
    weight: undefined,
    price: undefined,
    registerNo: undefined,
    version: undefined,
    producer: undefined,
    producePlace: undefined,
    origin: undefined,
    formula: undefined,
    material: undefined,
    feature: undefined,
    baseStrengthen: undefined,
    fineStrengthen: undefined,
    sort: undefined,
    status: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>
